package com.ruoyi.common.db;

import com.jfinal.plugin.activerecord.Record;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RecordUtil {
    /**
     * List<Record> 转 List<Map<String,Object>>
     * @param list
     * @return
     */
    public static List<Map<String,Object>> RecordListToMapList(List<Record> list)
    {
        List<Map<String,Object>> retrunList=new ArrayList<>();
        for(Record data:list)
        {
            retrunList.add(RecordToMap(data));
        }
        return retrunList;
    }
    /**
     * Record 转 Map<String,Object>
     * @param data
     * @return
     */
    public static Map<String,Object> RecordToMap(Record data)
    {
        Map<String,Object> retrunData=new HashMap<>();
        if(data!=null)
        {
            Map<String,Object> inpuData=data.getColumns();
            for(String key : inpuData.keySet()){
                String newKey=underlineToCamel(key,true);
                retrunData.put(newKey,inpuData.get(key));
            }
        }

        return retrunData;
    }
    /**
     * 下划线转驼峰法
     * @param line 源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underlineToCamel(String line,boolean smallCamel){
        if(line==null||"".equals(line)){
            return "";
        }
        StringBuffer sb=new StringBuffer();
        Pattern pattern= Pattern.compile("([A-Za-z\\d]+)(_)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(smallCamel&&matcher.start()==0?Character.toLowerCase(word.charAt(0)):Character.toUpperCase(word.charAt(0)));

            int index=word.lastIndexOf('_');
            if(index>0){
                sb.append(word.substring(1, index).toLowerCase());
            }else{
                sb.append(word.substring(1).toLowerCase());
            }

        }
        return sb.toString();
    }
    /**
     * 驼峰法转下划线
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camelToUnderline(String line){
        if(line==null||"".equals(line)){
            return "";
        }
        line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuffer sb=new StringBuffer();
        Pattern pattern= Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end()==line.length()?"":"_");
        }
        return sb.toString();
    }

    /**
     * List<Record> 转 List<Map<String,Object>>
     * @param list
     * @return
     */
    public static <T> List<T> RecordListToObjectList(List<Record> list,Class<T> clazz) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        List<T> retrunList=new ArrayList<>();
        for(Record data:list)
        {
            retrunList.add(recrodToJavaBean(data, clazz));
        }
        return retrunList;
    }
    public static  <T> T recrodToJavaBean(Record record, Class<T>  clazz) throws InstantiationException, IllegalAccessException, NoSuchFieldException {
        T vo = clazz.newInstance();

        if(record != null){
            String[] columns = record.getColumnNames();
            for(String col: columns){
                Field field = clazz.getDeclaredField(col);
                if(field != null){
                    if(!field.isAccessible()){
                        field.setAccessible(true);
                    }
                    field.set(vo, record.getObject(col));
                }
            }
        }
        return vo;
    }
    public static Record EntityToRecord(Object object)
    {
        Record retrunData=new Record();
        Map<String,Object> inpuData=entityToMap(object);
        for(String key : inpuData.keySet()){
            String newKey=camelToUnderline(key).toLowerCase();
            retrunData.set(newKey,inpuData.get(key));
        }
        return retrunData;
    }
    /**
     *
     * @description: 实体类转Map
     * @author: Jeff
     * @date: 2019年10月29日
     * @param object
     * @return
     */
    public static Map<String, Object> entityToMap(Object object) {
        Map<String, Object> map = new HashMap<>();
        for (Field field : object.getClass().getDeclaredFields()) {
            try {
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                Object o = field.get(object);
                if(!"serialVersionUID".equals(field.getName()))
                {
                    map.put(field.getName(), o);
                }
                field.setAccessible(flag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

}
